﻿"use strict";

var connection = new signalR.HubConnectionBuilder().withUrl("/gameHub").build();

var userName = document.getElementById("user-name");
var userID = document.getElementById("user-id");
var connectionID = document.getElementById("connection-id");
var score = document.getElementById("score");
var addScore = document.getElementById("add-score");
var messageList = document.getElementById("messages-list");

//Disable send button until connection is established
addScore.disabled = true;

function processRank(userList) {
    messageList.innerHTML = "";
    for (var i = 0; i < userList.length; i++) {
        var u = userList[i];
        var item = document.createElement("li");
        item.innerHTML = `${u.name}-${u.score}分`;
        messageList.appendChild(item);
        if (u.id === parseInt(userID.innerText)) {
            score.innerText = u.score;
        }
    }
}
function processFirstAccess(user, userList) {
    userName.innerText = user.name;
    score.innerText = user.score;
    userID.innerText = user.id;
    connectionID.innerText = user.connectionID;
    messageList.innerHTML = "";
    for (var i = 0; i < userList.length; i++) {
        var u = userList[i];
        var item = document.createElement("li");
        item.innerHTML = `${u.name} - ${u.score}分`;
        messageList.appendChild(item);
    }
}
connection.on("ReceiveRank", processRank);
connection.on("ReceiveUser", processFirstAccess);

window.onunload = function () {
    console.log("stop singal R ...");
    if (confirm("确定要退出吗？")) {
        connection.off("ReceiveRank", processRank);
        connection.off("ReceiveUser", processFirstAccess);
    }
};

connection.start()
    .then(function () {
        addScore.disabled = false;
    })
    .catch(function (err) {
        return console.error(err.toString());
    });

document.getElementById("add-score").addEventListener("click", function (event) {
    var score = Math.ceil((Math.random() + 1) * 100);
    connection
        .invoke("AddScore", parseInt(userID.innerText), score)
        .catch(function (err) {
            return console.error(err.toString());
        });
    event.preventDefault();
});